import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_footer.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/course.dart';
import 'package:kxy_flutter_app/view/course/course_item_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CourseListWidget extends StatefulWidget {
  final String cateId;
  final String searchText;

  const CourseListWidget({
    Key key,
    this.cateId,
    this.searchText,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return CourseListWidgetState();
  }
}

class CourseListWidgetState extends State<CourseListWidget> with AutomaticKeepAliveClientMixin {
  int page = 1;
  int totalCount = 0;
  Future loadFuture;
  RefreshController refreshController = new RefreshController();
  List<CourseProfile> courseList = new List<CourseProfile>();

  @override
  void initState() {
    super.initState();
    loadFuture = reload();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return FutureBuilder(
      future: loadFuture,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return body();
        }
        return LoadingWidget();
      },
    );
  }

  Widget body() {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      controller: refreshController,
      onLoading: () async {
        if (courseList.length < totalCount) {
          await loadMore();
          refreshController.loadComplete();
        } else {
          refreshController.loadNoData();
        }
      },
      onRefresh: () async {
        await reload();
        refreshController.refreshCompleted();
      },
      child: courseListWidget(),
    );
  }

  Widget courseListWidget() {
    if (courseList == null || courseList.length == 0) {
      return EmptyWidget(onRefresh: reload);
    }

    return ListView(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
      children: courseList.map((item) {
        return CourseItemWidget(
          course: item,
          callback: (id) => refreshStatus(id),
        );
      }).toList(),
    );
  }

  Future reload() async {
    page = 1;
    totalCount = 0;
    courseList.clear();
    await loadMore();
  }

  Future loadMore() async {
    var res = await Http.instance.post('/train-app/courseapp/getcourselist', params: {
      'orderType': 0,
      'page': page,
      'title': widget.searchText,
      'cateId': widget.cateId,
      'userId': Auth.instance.userId,
    });

    if (res.code == 200) {
      if (!mounted) return;
      setState(() {
        (res.data['list'] as List).forEach((item) {
          var courseItem = CourseProfile.fromJson(item);
          courseList.add(courseItem);
        });
        totalCount = res.data['totalCount'];
        page++;
      });
    }
  }

  Future refreshStatus(String courseId) async {
    var res = await Http.instance.post('/train-app/courseapp/courseStatus', params: {
      'courseId': courseId,
      'userId': Auth.instance.userId,
    });

    if (res.code == 200) {
      var existsCourse = courseList.singleWhere((element) => element.id == courseId);
      setState(() {
        existsCourse.status = CourseStatus.values[res.data];
      });
    }
  }

  @override
  bool get wantKeepAlive => true;
}
